import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def ftdata(path):
    df = pd.read_feather(path)
    return df[['trading_day','timestamp','clz']]

def f(df,label,k):
    df2 = df[['trading_day','timestamp',label]]
    df1 = ftdata("1m/"+label+".ft")
    df2 = pd.merge(df2, df1, on=['trading_day', 'timestamp'], how='left')
    if pd.isna(df2[label][0]):
        df2[[label,0]]=0
    df2['H'] = df2[label]/df2['clz']
    n,m = df2.shape
    tmp2 = np.append(np.array(np.NAN),np.array(df2['H'][:n-1])*np.array(df2['clz'][1:]))
    df2['tmp2'] = tmp2
    df2['V2'] = df2[label]-df2['tmp2']
    df2['tmp5'] = df2['clz'].diff()
    PNL = df2['H'].shift(1)*df2['tmp5']
    PNL[0]=0
    df2[label+'_PNL'] =PNL
    Total = df2['V2']*3/10000
    Total[0]=0
    df2[label+'_Total']=Total.abs()
    df2[label+'-SUM']=df2[label+'_PNL']-df2[label+'_Total']
    df2['Turnover1'] = df2['V2']/k
    df2[label+'Turnover2']= np.append(np.array(0),np.array(df2['Turnover1'][1:].sum() / (df2['Turnover1'][1:]!=np.nan).cumsum()))
    df2.to_csv("./csv/"+label+".csv")
    return df2[['trading_day','timestamp',label+'-SUM',label+'_PNL',label+'Turnover2']]

def main(path,k,name):
    df = pd.read_csv(path)
    columns = list(df.columns)
    SUM = df[['trading_day','timestamp']].copy()
    df1 = df.fillna(0)
    tmp = df1.loc[:,columns[2:]].apply(lambda x:x.sum(),axis=1)/k
    SUM['AvgLeverage'] = tmp
    n = len(columns)
    for i in range(2,n):
        tmpdf = f(df,columns[i],k)
        SUM = pd.merge(SUM, tmpdf, on=['trading_day', 'timestamp'], how='left')
    SUM = SUM.fillna(0)
    columns1 = SUM.columns
    c1 = []
    c2 = []
    c4 = []
    for columns in columns1:
        if 'Turnover2' in columns:
            SUM[columns] = SUM[columns]
            c4.append(columns)
        if '_PNL' in columns:
            c1.append(columns)
        if '-SUM' in columns:
            c2.append(columns)
    SUM['PNL']= SUM.loc[:,c1].apply(lambda x:x.sum(),axis=1)
    SUM['pnl'] =SUM['PNL'].cumsum()
    SUM['PNL_NET']= SUM.loc[:,c2].apply(lambda x:x.sum(),axis=1)
    SUM['pnl_net'] =SUM['PNL_NET'].cumsum()
    SUM['mean'] =SUM ['PNL_NET'].sum() / (SUM['PNL_NET']!=np.nan).sum()
    SUM['std']=SUM['PNL'][:i+1].std()
    SUM['sharp'] = SUM['mean']/SUM['std']*15.8
    SUM['Turnover']= SUM.loc[:,c4].apply(lambda x:x.sum(),axis=1)
    SUM['Total_Turnover'] =SUM['Turnover'].sum() / (SUM['Turnover']!=np.nan).sum()
    SUM['trading_day'] = pd.to_datetime(SUM['trading_day'],format='%Y%m%d')
    SUM.plot(x='trading_day',y='pnl_net',grid='true',figsize=(10,5),
             title='SharpRatio: %.2f, TurnOver: %.2f, AvgLeverage:%.2f'
            %(SUM.iloc[-1]['sharp'],SUM.iloc[-1]['Total_Turnover'],SUM.iloc[-1]['AvgLeverage']),
             color=('red'))
    SUM.to_csv("./csv/"+name+"-SUM.csv")
    plt.show()

main("./SampleTarget.csv",1,"SampleTarget")
main("./SampleTarget1.csv",1000000, "SampleTarget1")
main("./SampleTarget2.csv",1, "SampleTarget2")